package com.ityj.yygh.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ityj.yygh.hospital.service.DepartmentService;
import com.ityj.yygh.hospital.repository.ScheduleRepository;
import com.ityj.yygh.hospital.service.HospitalService;
import com.ityj.yygh.hospital.service.ScheduleService;
import com.ityj.yygh.model.hosp.BookingRule;
import com.ityj.yygh.model.hosp.Department;
import com.ityj.yygh.model.hosp.Hospital;
import com.ityj.yygh.model.hosp.Schedule;
import com.ityj.yygh.vo.hosp.BookingScheduleRuleVo;
import com.ityj.yygh.vo.hosp.ScheduleOrderVo;
import com.ityj.yygh.vo.hosp.ScheduleQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public boolean save(Map<String, Object> stringObjectMap) {

        // data verify and transfer to Department
        if (stringObjectMap == null) {
            log.warn("Input parameter stringObjectMap is null!");
            return false;
        }
        String jsonString = JSONObject.toJSONString(stringObjectMap);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);

        // verify existence
        Schedule existSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        if (existSchedule == null) {
            // not exist
            schedule.setIsDeleted(0);
            schedule.setCreateTime(new Date());
        } else {
            schedule.setIsDeleted(existSchedule.getIsDeleted());
            schedule.setCreateTime(existSchedule.getCreateTime());
        }
        schedule.setStatus(1);
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
        return true;
    }

    @Override
    public Page<Schedule> findScheduleByCondition(ScheduleQueryVo scheduleQueryVo, int pageNum, int pageSize) {
        // 创建Pageable对象，设置当前页及每页的大小
        // page – zero-based page index.
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        //创建Example对象，用于放查询的条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        // 根据前端传过来的departmentQueryVo，构造一个Department对象
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        Example<Schedule> example = Example.of(schedule, matcher);
        return scheduleRepository.findAll(example, pageable);
    }

    @Override
    public boolean remove(String hoscode, String hosScheduleId) {
        if (StringUtils.isAnyEmpty(hoscode, hosScheduleId)) {
            log.warn("Input param is incorrect!");
            return false;
        }

        // get schedule
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        // remove department
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
        return true;
    }

    // 根据医院编号和科室编号查询出排班规则数据
    @Override
    public Map<String, Object> findScheduleRule(Integer pageNum, Integer pageSize, String hoscode, String depcode) {
        // 1. 根据医院编号和科室编号进行查询：mongodb中schedule的数据
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        // 2. 根据工作日期workDate进行分组，可以用mongoTemplate的Aggregation进行分组查询
        // 3. 统计出对应日期的挂号数量，剩余数量等信息
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),   //匹配条件
                Aggregation.group("workDate") // 在mongodb中进行分组
                        .first("workDate").as("workDate")  // 取别名
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),

                // 排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),

                // 分页
                Aggregation.skip((pageNum - 1) * pageSize),
                Aggregation.limit(pageSize)
        );
        // 调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleList = aggregate.getMappedResults();

        // 分组查询的总记录数
        Aggregation totalCountAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),   //匹配条件
                Aggregation.group("workDate") // 在mongodb中进行分组
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(totalCountAgg, Schedule.class, BookingScheduleRuleVo.class);
        int totalCount = aggregationResults.getMappedResults().size();

        // 修改返回参数的类型：当前是星期几
        bookingScheduleRuleList.forEach(bookingScheduleRuleVo -> {
            String dayOfWeeks = getDayOfWeeks(bookingScheduleRuleVo.getWorkDate());
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeeks);
        });

        // 设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleList);
        result.put("total", totalCount);

        // 获取医院的名称
        String hosName = hospitalService.getHospName(hoscode);
        // 新建一个baseMap，便于管理数据
        Map<String, Object> baseMap = new HashMap<>();
        baseMap.put("hosName", hosName);

        result.put("baseMap", baseMap);
        return result;
    }

    @Override
    public List<Schedule> findScheduleDetail(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList = scheduleRepository.getScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        // 填充其他信息
        if (CollectionUtils.isEmpty(scheduleList)) {
            return new ArrayList<>();
        }
        // 医院名称，科室名称，对应星期几
        scheduleList.forEach(this::fillScheduleFields);
        return scheduleList;
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        // 根据预约周期，展示可预约日期数据，按分页展示
        Map<String, Object> result = new HashMap<>();
        //获取预约规则
        Hospital hospital = hospitalService.getHospitalByHoscode(hoscode);
        BookingRule bookingRule = hospital.getBookingRule();
        //获取可预约日期分页数据
        IPage<Date> iPage = this.getAvailableDateList(page, limit, bookingRule);

        //当前页可预约日期
        List<Date> dateList = iPage.getRecords();
        //获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        //获取科室剩余预约数

        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);

            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if (null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeeks(date);
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == len - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    @Override
    public Schedule getScheduleById(String scheduleId) {
        Schedule schedule = scheduleRepository.getScheduleById(scheduleId);
        if (schedule == null) {
            log.warn("Schedule数据为空！");
            return schedule;
        }
        this.fillScheduleFields(schedule);
        return schedule;
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //排班信息
        Schedule schedule = this.getScheduleById(scheduleId);

        //获取预约规则信息
        Hospital hospital = hospitalService.getHospitalByHoscode(schedule.getHoscode());
        BookingRule bookingRule = hospital.getBookingRule();

        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    private void fillScheduleFields(Schedule schedule) {
        if (schedule == null) {
            return;
        }
        // 医院名称，科室名称，对应星期几
        Map<String, Object> param = schedule.getParam();
        param.put("hosname", hospitalService.getHospName(schedule.getHoscode()));
        param.put("depname", departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        param.put("dayOfWeek", getDayOfWeeks(schedule.getWorkDate()));

    }


    private String getDayOfWeeks(Date date) {
        int dayOfWeek = new DateTime(date.getTime()).getDayOfWeek();
        String result = "";
        switch (dayOfWeek) {
            case DateTimeConstants.MONDAY:
                result = "星期一";
                break;
            case DateTimeConstants.TUESDAY:
                result = "星期二";
                break;
            case DateTimeConstants.WEDNESDAY:
                result = "星期三";
                break;
            case DateTimeConstants.THURSDAY:
                result = "星期四";
                break;
            case DateTimeConstants.FRIDAY:
                result = "星期五";
                break;
            case DateTimeConstants.SATURDAY:
                result = "星期六";
                break;
            case DateTimeConstants.SUNDAY:
                result = "星期日";
        }
        return result;
    }

    /**
     * 获取可预约日期分页数据
     */
    private IPage<Date> getAvailableDateList(int page, int limit, BookingRule bookingRule) {
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //预约周期
        int cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if (releaseTime.isBeforeNow()) cycle += 1;
        //可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        if (end > dateList.size()) end = dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
    }


}
